package com.xyy.controller;

import com.xyy.common.Result;
import com.xyy.entity.Activity;
import com.xyy.entity.Admin;
import com.xyy.dto.ActivityWithAdminDTO;
import com.xyy.service.ActivityService;
import com.xyy.service.AdminService;
import com.xyy.service.FileService;
import com.xyy.mapper.ActivityMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 活动管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/activity")
public class ActivityController {
    @Autowired
    private ActivityService activityService;
    
    @Autowired
    private AdminService adminService;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    private ActivityMapper activityMapper;
    
    /**
     * 创建活动
     */
    @PostMapping("/create")
    public Result<Activity> createActivity(@Valid @RequestBody Activity createDTO, 
                                         HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            Activity activity = activityService.createActivity(createDTO, adminId);
            return Result.success(activity);
        } catch (Exception e) {
            log.error("创建活动失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除活动
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteActivity(@PathVariable Long id, 
                                        HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            boolean success = activityService.deleteActivity(id, adminId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("活动不存在或无权限删除");
            }
        } catch (Exception e) {
            log.error("删除活动失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新活动
     */
    @PutMapping("/update")
    public Result<Activity> updateActivity(@Valid @RequestBody Activity activity, 
                                         HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            Activity updatedActivity = activityService.updateActivity(activity, adminId);
            return Result.success(updatedActivity);
        } catch (Exception e) {
            log.error("更新活动失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 上传活动封面
     */
    @PostMapping("/{id}/uploadCover")
    public Result<Map<String, String>> uploadCover(@PathVariable Long id,
                                                  @RequestParam("cover") MultipartFile file,
                                                  HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            
            // 验证文件
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }
            
            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !isValidImageFile(originalFilename)) {
                return Result.error("只支持jpg, jpeg, png, gif, bmp格式的图片");
            }
            
            // 验证文件大小（5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error("文件大小不能超过5MB");
            }
            
            // 上传封面并返回文件路径
            String coverPath = activityService.uploadCover(id, adminId, originalFilename, file.getBytes());
            
            // 构建完整的封面URL
            String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String fullCoverUrl = serverUrl + "/picture/" + coverPath;
            
            Map<String, String> result = new HashMap<>();
            result.put("coverUrl", fullCoverUrl);
            
            return Result.success("封面上传成功", result);
        } catch (Exception e) {
            log.error("活动封面上传失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取活动列表（所有用户可见）
     */
    @GetMapping("/list")
    public Result<List<Activity>> getActivityList() {
        try {
            List<Activity> activities = activityService.getActivityList();
            return Result.success(activities);
        } catch (Exception e) {
            log.error("获取活动列表失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取包含管理员信息的活动列表（所有用户可见）
     */
    @GetMapping("/listWithAdmin")
    public Result<List<ActivityWithAdminDTO>> getActivityListWithAdmin() {
        try {
            List<ActivityWithAdminDTO> activities = activityService.getActivityListWithAdmin();
            return Result.success(activities);
        } catch (Exception e) {
            log.error("获取包含管理员信息的活动列表失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据ID获取活动详情
     */
    @GetMapping("/{id}")
    public Result<Activity> getActivityById(@PathVariable Long id) {
        try {
            Activity activity = activityService.getActivityById(id);
            if (activity != null) {
                return Result.success(activity);
            } else {
                return Result.error("活动不存在");
            }
        } catch (Exception e) {
            log.error("获取活动详情失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取当前管理员创建的活动列表
     */
    @GetMapping("/admin/list")
    public Result<List<Activity>> getAdminActivityList(HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            List<Activity> activities = activityService.getActivityListByAdminId(adminId);
            return Result.success(activities);
        } catch (Exception e) {
            log.error("获取管理员活动列表失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取活动封面文件路径
     */
    @GetMapping("/{id}/cover")
    public Result<Map<String, String>> getCover(@PathVariable Long id, HttpServletRequest request) {
        try {
            String coverPath = activityService.getActivityCoverPath(id);
            if (coverPath != null) {
                // 构建完整的封面URL
                String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
                String fullCoverUrl = serverUrl + "/picture/" + coverPath;
                
                Map<String, String> result = new HashMap<>();
                result.put("coverUrl", fullCoverUrl);
                return Result.success("获取封面成功", result);
            } else {
                return Result.error("活动不存在或没有封面");
            }
        } catch (Exception e) {
            log.error("刷新活动封面URL失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    

    
    /**
     * 获取活动封面图片
     */
    @GetMapping("/cover/{filename}")
    public ResponseEntity<Resource> getActivityCover(@PathVariable String filename) {
        try {
            Resource resource = activityService.getActivityCover(filename);
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("获取活动封面失败: {}", e.getMessage());
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 验证图片文件类型
     */
    private boolean isValidImageFile(String filename) {
        if (filename == null) {
            return false;
        }
        
        String lowerFilename = filename.toLowerCase();
        return lowerFilename.endsWith(".jpg") || 
               lowerFilename.endsWith(".jpeg") || 
               lowerFilename.endsWith(".png") || 
               lowerFilename.endsWith(".gif") || 
               lowerFilename.endsWith(".bmp");
    }

    /**
     * 获取所有普通管理员的真实姓名
     */
    @GetMapping("/admin/names")
    @CrossOrigin
    public Result<List<String>> getAllNormalAdminNames() {
        try {
            List<String> adminNames = adminService.getAllNormalAdminRealNames();
            return Result.success(adminNames);
        } catch (Exception e) {
            log.error("获取普通管理员姓名列表失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据管理员真实姓名查询活动列表
     */
    @GetMapping("/admin/{realName}/activities")
    @CrossOrigin
    public Result<List<Activity>> getActivitiesByAdminName(@PathVariable String realName) {
        try {
            List<Activity> activities = activityService.getActivityListByAdminRealName(realName);
            return Result.success(activities);
        } catch (Exception e) {
            log.error("根据管理员姓名查询活动失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 审核活动（仅超级管理员）
     */
    @PostMapping("/{id}/audit")
    public Result<Boolean> auditActivity(@PathVariable Long id,
                                       @RequestParam boolean approved,
                                       @RequestParam(required = false) String auditComment,
                                       HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            boolean success = activityService.auditActivity(id, adminId, approved, auditComment);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            log.error("审核活动失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取待审核的活动列表（仅超级管理员）
     */
    @GetMapping("/pending-audit")
    public Result<List<Activity>> getPendingAuditActivities(HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            // 检查是否为超级管理员
            Admin admin = adminService.getAdminById(adminId);
            if (admin == null || admin.getLevel() != 2) {
                return Result.error("只有超级管理员才能查看待审核活动");
            }
            
            List<Activity> activities = activityService.getPendingAuditActivities();
            return Result.success(activities);
        } catch (Exception e) {
            log.error("获取待审核活动列表失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取所有活动列表（管理员端，包含所有状态）
     */
    @GetMapping("/admin/all")
    public Result<List<Activity>> getAllActivitiesForAdmin(HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("userId");
            // 检查是否为超级管理员
            Admin admin = adminService.getAdminById(adminId);
            if (admin == null || admin.getLevel() != 2) {
                return Result.error("只有超级管理员才能查看所有活动");
            }
            
            // 获取所有活动（包括待审核、已通过、已拒绝）
            QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("status", "PENDING_AUDIT", "APPROVED", "REJECTED");
            queryWrapper.orderByDesc("created_at");
            
            List<Activity> activities = activityMapper.selectList(queryWrapper);
            return Result.success(activities);
        } catch (Exception e) {
            log.error("获取所有活动列表失败", e);
            return Result.error(e.getMessage());
        }
    }
} 